﻿using System;
using System.IO;
using UnityEngine;
using System.Text;

namespace zFrame.Networks
{
    public class Request
    {
        private byte Flag = 1;
        protected int Len = 0;
        public int headCode;
        public string messageContent = "";

        public Request(){}
        public Request(object data, RequestCode requestCode) : this(data,(int)requestCode){}
        public Request(object data, int code)
        {
            if (data == null)
            {
                messageContent = "{}";
            }
            else
            {
                messageContent = JsonUtility.ToJson(data);
            }
            headCode = code;
        }

        /// <summary>
        /// 写入大端序的int
        /// </summary>
        /// <param name="value"></param>
        public byte[] WriterInt(int value)
        {

            byte[] bs = BitConverter.GetBytes(value);
            Array.Reverse(bs);
            return bs;
        }
        /// <summary>
        /// Writes the short.
        /// </summary>
        /// <returns>The short.</returns>
        /// <param name="value">Value.</param>
        public byte[] WriteShort(short value)
        {
            byte[] bs = BitConverter.GetBytes(value);
            Array.Reverse(bs);
            return bs;
        }

        /// <summary>
        ///  转换为 byte[]
        /// </summary>
        /// <returns></returns>
        public byte[] ToBytes()
        {
            byte[] _bytes; //自定义字节数组，用以装载消息协议
            using (MemoryStream memoryStream = new MemoryStream()) //创建内存流
            {
                BinaryWriter binaryWriter = new BinaryWriter(memoryStream, UTF8Encoding.Default); //以二进制写入器往这个流里写内容
                byte[] array = Encoding.UTF8.GetBytes(messageContent);
                //System.Text.Encoding gbk = System.Text.Encoding.GetEncoding("GBK");
                //byte[] array = gbk.GetBytes(messageContent);
                short messageContentLength = (short)array.Length;
                if (messageContentLength > 0)
                {
                    Len = (6 + messageContentLength);
                }
                else
                {
                    Len = (4 + messageContentLength);
                }
                binaryWriter.Write(Flag); //写入协议一级标志，占1个字节
                binaryWriter.Write(WriterInt(Len));//写入消息长度占4个字节
                binaryWriter.Write(WriterInt(headCode)); //消息头，占4个字节
                if (messageContentLength > 0)
                {
                    binaryWriter.Write(WriteShort(messageContentLength));
                    binaryWriter.Write(array); //写入实际消息内容
                }
                _bytes = memoryStream.ToArray(); //将流内容写入自定义字节数组
                binaryWriter.Close(); //关闭写入器释放资源
            }
            return _bytes; //返回填充好消息协议对象的自定义字节数组
        }
    }
}

